// pages/product-detail/product-detail.js
import {fileType, textRichFormat} from '../../utils/util'
const app = getApp()
const {globalData} = app

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productInfo: {}, // 基本信息
    deductionDes:[],//优惠描述
    productImgList: [], // 图片列表
    productSpecsList: [], // 规格
    maxRole: '0',
    detail: {}, // 富文本详情描述
    currentIndex: 0, // 商品图片滑动索引
    show: false, // 弹窗控制
    sheetTitle: '',
    currentSpecs: {}, // 选择的规格 
    selectCount: 1, // 选择的数量
    cartCount: 0, // 购物车数量
    user_id:'',//当前用户ID
    shareUserId:'',//分享人
  },
  // swiper切换
  swiperFinishHandle(event) {
    const {source, current} = event.detail
    if(source == 'touch') {
      this.setData({
        currentIndex: current
      })
    }
  },
  // 购物车点击
  shopCartHandle() {
    wx.navigateTo({
      url: '/pages/shop-cart/shop-cart',
    })
  },
  // 加入购物车
  addShopHandle() {
    this.setData({
      show: true,
      sheetTitle: '加入购物车',
      selectCount: 1
    })
  },
  // 立即购买
  buyHandle() {
    this.setData({
      show: true,
      sheetTitle: '立即购买',
      selectCount: 1
    })
  },
  countChange(event) {
    this.setData({
      selectCount: event.detail
    })
  },
  closeSheetHandle() {
    this,this.setData({
      show: false
    })
  },
  // 规格选择
  specsItemHandle(event) {
    const {index} = event.currentTarget.dataset || {index : 0}
    this.setData({
      selectCount: 1,
      currentSpecs: this.data.productSpecsList[index]
    })

  },
  confirmHanle() {
    const {sheetTitle, currentSpecs, selectCount} = this.data
    let data = {
      specs_id: currentSpecs.id,
      merchant_id: this.merchant_id,
      shareUserId: this.shareUserId,
      product_count: selectCount,
      product_id: currentSpecs.product_id
    }
    
    if (sheetTitle == '加入购物车') {
      this.requestAddShopCart(data)
    } else {
      if(selectCount <= 0) {
        return wx.showToast({
          title: '请添加数量',
        })
      }
      let listStr = encodeURIComponent(JSON.stringify([data]))
      this.setData({
        show: false
      })
      wx.navigateTo({
        url: `/pages/shop-list/shop-list?shareUserId=${this.shareUserId}&productList=${listStr}`,
      })
    }
  },
  // 添加商品到购物车
  requestAddShopCart(data) {
    wx.ajax.post('addOrderCart.action', data, true).then(res => {
      this.setData({
        show: false
      }, () => {
        app.requestShopCart((data) => {
          this.setData({
            cartCount: data.length
          })
        })
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
      })
    })
  },
  // 请求产品详情
  requestProductDetail(productId, merchant_id) {
    wx.ajax.post('findProductInfoById.action', {id: productId, merchant_id}).then(res => {
      const {product_info,maxRole,deductionDes, productSpecsList = [], productImgList, productDetail = {}, productMerchantRel = {}} = res.result

      productSpecsList.forEach(item => {
        item.specs_img = globalData.imageUrl + item.specs_img
      })

      product_info.prel_min_price = productMerchantRel.prel_min_price
      this.setData({
        productInfo: product_info,
        maxRole:maxRole,
        deductionDes:deductionDes,
        productImgList: productImgList.map(item => {
          item.fileType = fileType(item.image_url)
          item.image_url = globalData.imageUrl + item.image_url
          return item
        }),
        productSpecsList: productSpecsList,
        currentSpecs: productSpecsList[0] || {},
        detail: {
          product_detail: textRichFormat(productDetail.product_detail || '')
        }
      })
    })
  },
  getData() {
    wx.ajax.post("getInvitationParam.action", {}, false).then((res) => {
      if (res.success) {
        const result = res.result;

        this.setData({
          user_id: result.userId,
        });
      }
    });
  },

  setShopCart() {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.getData();
    const {productId, merchant_id,shareUserId} = options

    this.options = options
    this.merchant_id = merchant_id
    this.shareUserId = shareUserId;
    this.requestProductDetail(productId, merchant_id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!globalData.shopCart) {
      app.requestShopCart((data) => {
        this.setData({
          cartCount: data.length
        })
      })
    } else {
      this.setData({
        cartCount: globalData.shopCart.length
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onShareTimeline() {
    let shareUserId = this.data.user_id;
    let image = this.data.productImgList.find(item => item.fileType == 'image')
    return {
      title: this.data.productInfo.product_name,
      path: `/pages/product-detail/product-detail?productId=${this.options.productId}&merchant_id=${this.options.merchant_id}&shareUserId=${shareUserId}`,
      imageUrl: image ? image.image_url : null
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let shareUserId = this.data.user_id;
    let image = this.data.productImgList.find(item => item.fileType == 'image')
    return {
      title: this.data.productInfo.product_name,
      path: `/pages/product-detail/product-detail?productId=${this.options.productId}&merchant_id=${this.options.merchant_id}&shareUserId=${shareUserId}`,
      imageUrl: image ? image.image_url : null
    }
  }
})